package com.dubbo.oneclass;

import com.dubbo.oneclass.bean.User;
import org.apache.dubbo.config.*;
import org.junit.Test;

import java.io.IOException;

public class DubboCluster {

    @Test
    public void server1() throws IOException {
        openServer(12345);
    }

    @Test
    public void server2() throws IOException {
        openServer(12346);
    }

    @Test
    public void server3() throws IOException {
        openServer(12347);
    }


    /**
     * 1、创建ServiceConfig
     * 2、配置应用=》配置协议=》配置注册中心=》配置接口=》配置实现类
     *
     * @param port
     */
    public void openServer(Integer port) throws IOException {
        ServiceConfig<Object> objectServiceConfig = new ServiceConfig<>();
        ApplicationConfig applicationConfig = new ApplicationConfig("my-server");
        objectServiceConfig.setApplication(applicationConfig);
        ProtocolConfig protocolConfig = new ProtocolConfig("dubbo");
        protocolConfig.setPort(port);
        objectServiceConfig.setProtocol(protocolConfig);
        // zookeeper 注册中心
        RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181");
        // 广播模式：https://blog.csdn.net/qq924862077/article/details/79659498
//        RegistryConfig registryConfig = new RegistryConfig("multicast://224.1.1.1:2223");
        objectServiceConfig.setRegistry(registryConfig);
        objectServiceConfig.setInterface(UserService.class);
        objectServiceConfig.setRef(new UserServiceImpl(port));
        objectServiceConfig.export();
        System.in.read();
    }


    public static void main(String[] args) {
        UserService client = getClient();
        // 多次调用，会自动负载均衡
        for (int i = 0; i < 30; i++) {
            User user = client.getUser(666);
            System.out.println(user);
        }
    }

    /**
     * 客户端
     * <p>
     * 1、创建ReferenceConfig
     * 2、配置应用=》配置注册中心=》配置接口=》获取实现类
     *
     * @return
     */
    public static UserService getClient() {
        ReferenceConfig<UserService> objectReferenceConfig = new ReferenceConfig<>();
        ApplicationConfig applicationConfig = new ApplicationConfig("my-client");
        objectReferenceConfig.setApplication(applicationConfig);
        // zookeeper 注册中心
//        RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181");

        // 广播模式：https://blog.csdn.net/qq924862077/article/details/79659498
        RegistryConfig registryConfig = new RegistryConfig("multicast://224.1.1.1:2223");
        objectReferenceConfig.setRegistry(registryConfig);
        objectReferenceConfig.setInterface(UserService.class);
        return objectReferenceConfig.get();
    }
}
